/**
 * @description 爬取青年大学习latest一期网页元素,生成完成学习的界面
 */
const Koa = require('koa');
const axios = require('axios');
const cheerio = require('cheerio');
const app = new Koa();

const PORT = 5858; //服务端口

const selector1 = '.school dt.dtsty1 > a';
const selector2 = 'ul.movie-list > li:first-child > a:first-child';
const reg = /\/[a-z0-9]{10}\//g;

let total = 0;

app.use(async (ctx) => {
  ctx.response.type = 'text/html';
  ctx.body = await Deal();
  ++total % 2 == 0
    ? console.log('visitor +1,total: ' + total / 2, new Date())
    : null;
});

async function Deal() {
  const page1 = await getPage('http://www.cyol.com/'); //中青网页面
  let links = cheerio.load(page1)(selector1);
  let str = '';
  links.each(function (index) {
    let text = cheerio.load(this).text();
    if (text.indexOf('青年大学习') > -1) {
      str = this.attribs['href']; //青年大学习页面地址
      return false;
    }
  });

  const page2 = await getPage(str); //青年大学习页
  links = cheerio.load(page2)(selector2);
  str = links[0].attribs['href']; //最新一期大学习地址

  const page3 = await getPage(str); //最新青年大学习
  var title = cheerio.load(page3)('title:first');
  title = cheerio.load(title[0]).text(); //获取标题

  if (reg.test(str)) {
    // 提取hash
    str = str.match(reg)[0];
  }
  return getDoc(str, title);
}

async function getPage(url) {
  // 请求页面HTML
  return axios
    .get(url, {
      headers: {
        'User-Agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36',
      },
    })
    .then((res) => {
      if (res.status == 200) return res.data;
      else return 'get page fail';
    });
}
/**
 * 利用模板,返回对应网页
 * @param {string} str 地址中hash码,10位
 * @param {string} title 页面标题
 * @returns
 */
function getDoc(str, title) {
  return `<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>${title}</title>
    <style type="text/css">
      * {
        padding: 0;
        margin: 0;
      }
      #bk {
        position: absolute;
        top: 0;
        left: 0;
        height: 100vh;
        overflow: hidden;
        z-index: -1;
      }
    </style>
  </head>
  <body>
    <img id="bk" src="http://h5.cyol.com/special/daxuexi${str}images/end.jpg" />
  </body>
  <script>
    var img = document.getElementById("bk");
    /(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)
      ? img.style.width = "100vw"
      : alert("请用移动端打开此网页呢~");
  </script>
</html>`;
}
app.listen(PORT, () => {
  console.log('starting at port: ' + PORT);
});
